import axios from 'axios'
import qs from 'qs'
import {
    Message,
    Loading
} from 'element-ui'
import router from '@/router';
const baseURL = process.env.VUE_APP_API_URL;

// 封装全局axios
const http = axios.create({
    // baseURL:'http://backend.pms.cn',
    baseURL: 'http://backend.pms.cn/backend',
    // baseURL: baseURL,
    timeout: 9000
})

// 让实例支持流操作
http.all = axios.all;


//  添加请求拦截器
http.interceptors.request.use(function (config) {
    // 发送请求前提示加载信息
    // loadingHttp.service()
    // 判断是否含有请求头,如果没有主动认证,从存储中获取
    if (!config.headers["Authorization"]) {
        const tokenName = process.env.VUE_APP_TOKEN_KEY;
        const token = window.sessionStorage.getItem(tokenName) || window.localStorage.getItem(tokenName);
        if (token) config.headers.Authorization = `Bearer ${token}`;
    }
    // post 请求
    if (config.method == 'post') {
        if (config.headers["Content-Type"] == "multipart/form-data") {
            // 如果是上传文件, 那么将全局10秒超时机制取消
            config.timeout = 0;
        } else {
            // 否则对参数进行转换发送, 不转换常规后端接收不到
            config.data = qs.stringify(config.data);
        }
    }

    return config;
}, function (error) {
    // Do something with request error
    return Promise.reject(error);

});

// Add a response interceptor
// 添加相应拦截器
http.interceptors.response.use(function (res) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    // 数据加载完成,关闭loading
    /*  this.$nextTick(()=>{
         loadingHttp.close();
     }) */
    // 处理响应状态码(是200的情况)
    if (res.status === 200) {
        // return Promise.resolve(res)
        // 判断状态码状态
        // 401 登录信息过期,重新登录
        if (res.data.code == 401) {
            Message.error(res.data.msg)
            setTimeout(() => {
                router.replace({
                    path: '/login',
                });
            }, 1000);
        }
    } else {
        Message.error(res.statusText);
        // return Promise.reject(res)
    }
    return res;
}, function (error) {
    // Message.error(error.message)
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    // 状态码不是200的情况
    console.log('error')

    return Promise.reject(error);
});

// 将创建的实例挂载在Vue原型上(无需import导入)
/* Vue.prototype.$http = http;
Vue.prototype.$get = http.get;
Vue.prototype.$post = http.post; */
export default http;